﻿$(document).ready(function () {
    $("#ingredient-boxes").fadeIn()
    .find("input[type=checkbox]")
    .click(function () {
        $("#ingredients").val(
            $.map($("#ingredient-boxes input[type=checkbox]:checked"), function (elem) {
                return $(elem).val();
            }).join(", ")
        );
    });

    $("#search-submit").click(function () {
        window.location.hash = "/" + $("#ingredients").val();
        return false;
    });

    Sammy(function () {
        var results = $("#recipe-search-results-container");
        this.get("#/:ingredients", function () {
            var ingredients =
                $.map(this.params["ingredients"].split(","), function (elem) {
                    return $.trim(elem);
                });
            var ingredientsCaps =
                $.map(ingredients, function (elem) {
                    return elem.toUpperCase();
                });
            $("#ingredient-boxes input[type=checkbox]").attr("checked", null).each(function () {
                if ($.inArray($(this).val().toUpperCase(), ingredientsCaps) != -1)
                    $(this).attr("checked", "checked");
            });
            $("#ingredients").val(ingredients.join(", "));

            results.fadeOut(100);
            $.ajax({
                url: results.attr("data-onlyrecipes-url"),
                data: "ingredients=" + this.params["ingredients"],
                success: function (data) {
                    results.html(data);
                    results.fadeIn(250);
                }
            });
        });
    }).run();
});